<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item :to="{ path: '/institution/notices' }">
                <i class="el-icon-document"></i>
                系统公告
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                {{ pageTitle }}
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row
                style="margin-top: 10px"
                type="flex"
                justify="end"
            >
                <el-button
                    @click="cancel"
                    style="margin-right: 10px;"
                    type="primary"
                    size="mini"
                >取消
                </el-button>
                <el-button
                    @click="preview"
                    :disabled="!noticeForm.id"
                    style="margin-right: 10px;"
                    type="primary"
                    size="mini"
                >预览
                </el-button>
                <el-button
                    @click="save"
                    style="margin-right: 10px;"
                    type="primary"
                    size="mini"
                >保存
                </el-button>
                <el-button
                    v-if="this.noticeForm.status !== 2"
                    @click="publish"
                    style="margin-right: 10px;"
                    type="primary"
                    size="mini"
                >发布
                </el-button>
                <el-button
                    v-else
                    @click="finish"
                    style="margin-right: 10px;"
                    type="primary"
                    size="mini"
                >结束
                </el-button>
            </el-row>
            <el-form
                ref="noticeForm"
                :model="noticeForm"
                :rules="noticeFormRules"
                label-width="80px"
            >
                <el-form-item
                    label="标题"
                    prop="title"
                >
                    <el-input
                        v-model="noticeForm.title"
                        placeholder="请输入公告标题"
                        class="input-form"
                        size="mini"
                    ></el-input>
                    <span>当前状态：{{ noticeStatusName }}</span>
                </el-form-item>
                <el-form-item
                    label="类型"
                    prop="type"
                    style="margin-top: 10px"
                >
                    <el-select
                        v-model="noticeForm.type"
                        class="picker-form"
                        placeholder="请选择公告类型"
                        size="mini"
                    >
                        <el-option
                            v-for="item in noticeTypeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="摘要"
                    prop="summary"
                    style="margin-top: 15px; min-height: 41px"
                >
                    <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入公告摘要"
                        v-model="noticeForm.summary"
                        size="mini"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="内容"
                    style="margin-top: 15px"
                >
                    <div ref="noticeFormEditor"></div>
                </el-form-item>
                <el-form-item
                    label="结束时间"
                    prop="deadline"
                    style="margin-top:10px;"
                >
                    <el-date-picker
                        v-model="noticeForm.deadline"
                        placeholder="选择结束时间"
                        value-format="timestamp"
                        class="picker-form"
                        type="datetime"
                        size="mini"
                    >
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import E from 'wangeditor';
import { vxRule } from '@/client/libs/validator';
import { DateUtil } from '@/client/libs/date';

export default {
    name: 'InstitutionNoticesEdit',
    data() {
        const checkTitle = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请输入公告标题');
            } else {
                callback();
            }
        };
        const checkType = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请选择公告类型');
            } else {
                callback();
            }
        };
        return {
            noticeID: 0,
            noticeForm: {
                title: '',
                type: '',
                summary: '',
                content: '',
                deadline: '',

                status: 1,
            },
            noticeFormRules: {
                title: [
                    vxRule(true, null, 'blur', '请填写标题'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '标题填写请不要超过255个字符',
                        null,
                        255
                    ),
                ],
                type: [vxRule(true, null, 'blur', '请选择类型')],
                summary: [
                    vxRule(
                        false,
                        'length',
                        'blur',
                        '摘要填写请不要超过255个字符',
                        null,
                        255
                    ),
                ],
                deadline: [vxRule(true, null, 'blur', '请选择结束时间')],
            },
            noticeTypeList: [],
            noticeFormEditor: null,
        };
    },
    mounted() {
        this.noticeTypeRequest();
        // 内容富文本编辑器初始化
        const that = this;
        this.noticeFormEditor = new E(this.$refs.noticeFormEditor);
        this.noticeFormEditor.customConfig = {
            onchange(html) {
                that.noticeForm.content = html;
            },
            // TODO 图片上传
            uploadImgServer: '/api/UploadImg', // 上传图片到服务器
            uploadFileName: 'Content', // 后端使用这个字段获取图片信息
            uploadImgMaxLength: 1, // 限制一次最多上传 1 张图片
            zIndex: 0,
        };
        this.noticeFormEditor.create();

        const id = this.$store.state.noticeID;
        if (id) {
            this.noticeID = id;
            this.noticeForm.id = id;
            this.noticeRequest(id);
        }
    },
    computed: {
        noticeStatusName() {
            let statusName = '';
            switch (this.noticeForm.status) {
                case 0:
                    statusName = '已结束';
                    break;
                case 1:
                    statusName = '暂存';
                    break;
                case 2:
                    statusName = '已发布';
                    break;
                default:
            }
            return statusName;
        },
        requestTipMessage() {
            let tipMessage = '';
            switch (this.noticeForm.status) {
                case 0:
                    tipMessage = '已成功结束发布该公告';
                    break;
                case 1:
                    tipMessage = '已成功保存该公告';
                    break;
                case 2:
                    tipMessage = '已成功发布该公告';
                    break;
                default:
            }
            return tipMessage;
        },
        pageTitle() {
            return this.noticeID ? '编辑公告' : '新增公告';
        },
    },
    methods: {
        cancel() {
            this.$router.go(-1);
        },
        preview() {
            this.$store.commit('setPropertyGeneral', {
                key: 'noticeID',
                value: this.noticeForm.id,
            });
            const width = window.screen.availWidth + 10;
            const height = window.screen.availHeight + 10;
            window.open(`/notices/preview/${this.noticeForm.id}`, '_blank', `location=no,width=${width},height=${height}`);
        },
        save() {
            if (this.validateForm()) {
                if (this.noticeForm.deadline < new Date().getTime() + 2000) {
                    this.$message.warning({
                        message: '结束时间不得小于当前时间',
                    });
                    return;
                }
                this.noticeSave();
            }
        },
        publish() {
            if (this.validateForm()) {
                if (this.noticeForm.deadline < new Date().getTime() + 2000) {
                    this.$message.warning({
                        message: '结束时间不得小于当前时间',
                    });
                    return;
                }
                this.noticeForm.status = 2;
                this.noticeSave();
            }
        },
        finish() {
            this.noticeForm.status = 0;
            this.noticeForm.deadline = new Date().getTime() + 2000;
            this.noticeSave();
        },
        validateForm() {
            let decide = false;
            this.$refs.noticeForm.validate((valid) => {
                if (valid) {
                    decide = true;
                }
            });
            return decide;
        },
        async noticeTypeRequest() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: {
                        code: 'noticeType',
                        page: 0,
                        size: 99,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    // 查询结果数据
                    result.data.forEach((t) => {
                        this.noticeTypeList.push({
                            id: t.id,
                            name: t.name,
                        });
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        async noticeRequest(id) {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: `/PROXY-Remote/notices/${id}`,
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    // 查询结果数据
                    Object.keys(this.noticeForm).forEach((key) => {
                        if (key === 'deadline') {
                            this.noticeForm[key] = DateUtil.parseDate(
                                result.data[key]
                            ).getTime();
                        } else {
                            this.noticeForm[key] = result.data[key];
                        }
                    });
                    this.noticeFormEditor.txt.html(this.noticeForm.content);
                });
            } catch (e) {
                // 跳出
            }
        },
        async noticeSave() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: this.noticeID ? 'PUT' : 'POST',
                    url: '/PROXY-Remote/notices',
                    data: this.noticeForm,
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }
                    // 请求成功
                    this.noticeForm.id = res.data.data.id;
                    this.noticeForm.deadline = new Date(
                        res.data.data.deadline
                    ).getTime();
                    this.$message.success(`${this.requestTipMessage}`);
                    this.$router.push('/institution/notices');
                });
            } catch (e) {
                // 跳出
                this.$message.error('操作失败');
            }
        },
    },
};
</script>

<style scoped>
</style>
